{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Title: #Queue Reconstruction by Height"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Difficulty: #Medium"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Category Title: #Algorithms"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Tag Slug: #greedy #binary-indexed-tree #segment-tree #array #sorting"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Name Translated: #贪心 #树状数组 #线段树 #数组 #排序"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solution Name: reconstructQueue"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Title: #根据身高重建队列"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Translated Content:\n",
    "<p>假设有打乱顺序的一群人站成一个队列，数组 <code>people</code> 表示队列中一些人的属性（不一定按顺序）。每个 <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> 表示第 <code>i</code> 个人的身高为 <code>h<sub>i</sub></code> ，前面 <strong>正好</strong> 有 <code>k<sub>i</sub></code><sub> </sub>个身高大于或等于 <code>h<sub>i</sub></code> 的人。</p>\n",
    "\n",
    "<p>请你重新构造并返回输入数组 <code>people</code> 所表示的队列。返回的队列应该格式化为数组 <code>queue</code> ，其中 <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> 是队列中第 <code>j</code> 个人的属性（<code>queue[0]</code> 是排在队列前面的人）。</p>\n",
    "\n",
    "<p> </p>\n",
    "\n",
    "<ul>\n",
    "</ul>\n",
    "\n",
    "<p><strong>示例 1：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]\n",
    "<strong>输出：</strong>[[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\n",
    "<strong>解释：</strong>\n",
    "编号为 0 的人身高为 5 ，没有身高更高或者相同的人排在他前面。\n",
    "编号为 1 的人身高为 7 ，没有身高更高或者相同的人排在他前面。\n",
    "编号为 2 的人身高为 5 ，有 2 个身高更高或者相同的人排在他前面，即编号为 0 和 1 的人。\n",
    "编号为 3 的人身高为 6 ，有 1 个身高更高或者相同的人排在他前面，即编号为 1 的人。\n",
    "编号为 4 的人身高为 4 ，有 4 个身高更高或者相同的人排在他前面，即编号为 0、1、2、3 的人。\n",
    "编号为 5 的人身高为 7 ，有 1 个身高更高或者相同的人排在他前面，即编号为 1 的人。\n",
    "因此 [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] 是重新构造后的队列。\n",
    "</pre>\n",
    "\n",
    "<p><strong>示例 2：</strong></p>\n",
    "\n",
    "<pre>\n",
    "<strong>输入：</strong>people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]\n",
    "<strong>输出：</strong>[[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]\n",
    "</pre>\n",
    "\n",
    "<p> </p>\n",
    "\n",
    "<p><strong>提示：</strong></p>\n",
    "\n",
    "<ul>\n",
    "\t<li><code>1 <= people.length <= 2000</code></li>\n",
    "\t<li><code>0 <= h<sub>i</sub> <= 10<sup>6</sup></code></li>\n",
    "\t<li><code>0 <= k<sub>i</sub> < people.length</code></li>\n",
    "\t<li>题目数据确保队列可以被重建</li>\n",
    "</ul>\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Description: [queue-reconstruction-by-height](https://leetcode.cn/problems/queue-reconstruction-by-height/description/)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Solutions: [queue-reconstruction-by-height](https://leetcode.cn/problems/queue-reconstruction-by-height/solutions/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_cases = ['[[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]', '[[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        sortpeople = sorted(people)\n",
    "        queue = [0] * len(people)\n",
    "        for p in sortpeople:\n",
    "            k = p[1] + 1\n",
    "            for i in range(len(queue)):\n",
    "                if queue[i] == 0 or queue[i][0] == p[0]:\n",
    "                    k -= 1\n",
    "                if k == 0 and queue[i] == 0:\n",
    "                    queue[i] = p\n",
    "        return queue\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        que = []\n",
    "        for p in people:\n",
    "            que.insert(p[1], p)\n",
    "        return que\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 先倒序排列，再依次遍历处理每个元素:按序号直接将元素插入结果即可\n",
    "        # 因为倒序排序后，当前元素前的元素都是大于等于它的元素\n",
    "\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        res = []\n",
    "        for p in people:\n",
    "            res.insert(p[1],p)\n",
    "\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 先按照身高从高到低排队\n",
    "        # 随后再根据k插入\n",
    "        people = sorted(people, key=lambda x: (-x[0], x[1]))\n",
    "        res = []\n",
    "\n",
    "        for p in people:\n",
    "            res.insert(p[1], p)\n",
    "        \n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# 406.\n",
    "# 根据身高重建队列\n",
    "# 假设有打乱顺序的一群人站成一个队列，数组\n",
    "# people\n",
    "# 表示队列中一些人的属性（不一定按顺序）。每个\n",
    "# people[i] = [hi, ki]\n",
    "# 表示第\n",
    "# i\n",
    "# 个人的身高为\n",
    "# hi ，前面\n",
    "# 正好\n",
    "# 有\n",
    "# ki\n",
    "# 个身高大于或等于\n",
    "# hi\n",
    "# 的人。\n",
    "#\n",
    "# 请你重新构造并返回输入数组\n",
    "# people\n",
    "# 所表示的队列。返回的队列应该格式化为数组\n",
    "# queue ，其中\n",
    "# queue[j] = [hj, kj]\n",
    "# 是队列中第\n",
    "# j\n",
    "# 个人的属性（queue[0]\n",
    "# 是排在队列前面的人）。\n",
    "#\n",
    "#\n",
    "#\n",
    "# 示例\n",
    "# 1：\n",
    "#\n",
    "# 输入：people = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]\n",
    "# 输出：[[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]\n",
    "# 解释：\n",
    "# 编号为\n",
    "# 0\n",
    "# 的人身高为\n",
    "# 5 ，没有身高更高或者相同的人排在他前面。\n",
    "# 编号为\n",
    "# 1\n",
    "# 的人身高为\n",
    "# 7 ，没有身高更高或者相同的人排在他前面。\n",
    "# 编号为\n",
    "# 2\n",
    "# 的人身高为\n",
    "# 5 ，有\n",
    "# 2\n",
    "# 个身高更高或者相同的人排在他前面，即编号为\n",
    "# 0\n",
    "# 和\n",
    "# 1\n",
    "# 的人。\n",
    "# 编号为\n",
    "# 3\n",
    "# 的人身高为\n",
    "# 6 ，有\n",
    "# 1\n",
    "# 个身高更高或者相同的人排在他前面，即编号为\n",
    "# 1\n",
    "# 的人。\n",
    "# 编号为\n",
    "# 4\n",
    "# 的人身高为\n",
    "# 4 ，有\n",
    "# 4\n",
    "# 个身高更高或者相同的人排在他前面，即编号为\n",
    "# 0、1、2、3\n",
    "# 的人。\n",
    "# 编号为\n",
    "# 5\n",
    "# 的人身高为\n",
    "# 7 ，有\n",
    "# 1\n",
    "# 个身高更高或者相同的人排在他前面，即编号为\n",
    "# 1\n",
    "# 的人。\n",
    "# 因此[[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]\n",
    "# 是重新构造后的队列。\n",
    "# 示例\n",
    "# 2：\n",
    "#\n",
    "# 输入：people = [[6, 0], [5, 0], [4, 0], [3, 2], [2, 2], [1, 4]]\n",
    "# 输出：[[4, 0], [5, 0], [2, 2], [3, 2], [1, 4], [6, 0]]\n",
    "#\n",
    "# 提示：\n",
    "#\n",
    "# 1 <= people.length <= 2000\n",
    "# 0 <= hi <= 106\n",
    "# 0 <= ki < people.length\n",
    "# 题目数据确保队列可以被重建\n",
    "\n",
    "# 思路： 链表法：\n",
    "from typing import List\n",
    "\n",
    "\n",
    "class Node:\n",
    "\n",
    "    def __init__(self, val=-1, val2=-1, next=None):\n",
    "        self.val = val\n",
    "        self.val2 = val2\n",
    "        self.next = next\n",
    "\n",
    "\n",
    "def printNode(node: Node):\n",
    "    if node is not None:\n",
    "        print(node.val)\n",
    "        printNode(node.next)\n",
    "\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        self.people = people\n",
    "        # ordered_list = []\n",
    "        size = len(people)\n",
    "        for i in range(size):\n",
    "            for j in range(i, size):\n",
    "                if people[i][0] == people[j][0]:\n",
    "                    if people[i][1] > people[j][1]:\n",
    "                        self.change(i, j)\n",
    "                if people[i][0] < people[j][0]:\n",
    "                    self.change(i, j)\n",
    "        print(people)\n",
    "\n",
    "        root = Node()\n",
    "        for ele in self.people:\n",
    "            newNode = Node(ele[0], ele[1])\n",
    "            tmp = root\n",
    "            position = 0\n",
    "            while position < ele[1]:\n",
    "                tmp = tmp.next\n",
    "                position += 1\n",
    "            if tmp.next is not None:\n",
    "                newNode.next = tmp.next\n",
    "            tmp.next = newNode\n",
    "        printNode(root)\n",
    "        res = []\n",
    "        tmp = root.next\n",
    "        while tmp is not None:\n",
    "            res.append([tmp.val, tmp.val2])\n",
    "            tmp = tmp.next\n",
    "        return res\n",
    "\n",
    "    def change(self, i, j):\n",
    "        tmp = self.people[i]\n",
    "        self.people[i] = self.people[j]\n",
    "        self.people[j] = tmp\n",
    "\n",
    "\n",
    "people = [[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]\n",
    "res = Solution().reconstructQueue(people)\n",
    "print(res)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key = lambda x: (-x[0], x[1]))\n",
    "        res = []\n",
    "        for p in people:\n",
    "            if p[1] == len(res):\n",
    "                res.append(p)\n",
    "            else:\n",
    "                res.insert(p[1], p)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from sortedcontainers import SortedDict\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        d = defaultdict(set)\n",
    "        for h, k in people:\n",
    "            d[h].add(k)\n",
    "        d1 = {k: sorted(v, reverse=True) for k, v in d.items()}\n",
    "        d = SortedDict(d)\n",
    "        a = []\n",
    "        while d:\n",
    "            for i in d:\n",
    "                if 0 not in d[i]:\n",
    "                    continue\n",
    "                a.append([i, d1[i].pop()])\n",
    "                d[i].remove(0)\n",
    "                for j in d:\n",
    "                    if j > i:\n",
    "                        break\n",
    "                    d[j] = {k - 1 for k in d[j]}\n",
    "                if not d[i]:\n",
    "                    del d[i]\n",
    "                break\n",
    "        return a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, pp: List[List[int]]) -> List[List[int]]:\n",
    "        pp.sort(key = lambda x: (x[0], -x[1]))\n",
    "        from sortedcontainers import SortedList\n",
    "        res = [[] for _ in range(0, len(pp))]\n",
    "        for p in pp:\n",
    "            cnt = 0\n",
    "            for r in res:\n",
    "                if len(r) == 0:\n",
    "                    cnt += 1\n",
    "                if cnt == p[1] + 1:\n",
    "                    r += p\n",
    "                    break           \n",
    "        return res\n",
    "            \n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        res = []\n",
    "        people =sorted(people,key = lambda x : (-x[0], x[1]))\n",
    "        for p in people:\n",
    "            if p[1] >= len(res):\n",
    "                res.append(p)\n",
    "            else:\n",
    "                res.insert(p[1],p)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "\n",
    "        people = list(sorted(people, key= lambda x: (x[0], -x[1]), reverse= True))\n",
    "        # print(people)\n",
    "\n",
    "        result = []\n",
    "        for person in people:\n",
    "            result.insert(person[1], person)\n",
    "\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 类比分发糖果的题目，遇到两个维度都需要考虑的时候不要两个维度都去考虑\n",
    "        # 先确定一个维度，再去确定另一个维度，一个维度走不通，另一个维度大概率可以走通\n",
    "        # 先对身高从大到小进行排序，则越往后的排序身高越低，将其排在前方不会影响前方人的k值\n",
    "        # 直接按照后方人的k值在数组内部进行插入(新建立一个数组，在原有数组上修改会影响遍历的过程)\n",
    "        # python sort函数和lambda的使用，实现按关键字排序\n",
    "        people.sort(key = lambda x:(-x[0],x[1])) # -x[0]表示身高降序,x[1]表示k升序\n",
    "        length = len(people)\n",
    "        queue = []\n",
    "        \n",
    "        # 当前的列表已经按照身高的降序完成了排列，直接按照k值对queue进行插入\n",
    "        for i in people:\n",
    "            queue.insert(i[1], i) \n",
    "            # list.insert(index, item_value),index插入位置的索引数，item_value插入的数值\n",
    "        return queue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key = lambda x: (x[0], -x[1]), reverse = True)\n",
    "        i = 0\n",
    "        for i in range(1, len(people)):\n",
    "            if people[i][0] == people[i - 1][0]:\n",
    "                continue\n",
    "            else:\n",
    "                k = i\n",
    "                temp = people[i]\n",
    "                while k > temp[1]:\n",
    "                    people[k] = people[k - 1]\n",
    "                    k -= 1\n",
    "                people[k] = temp\n",
    "        return people"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "\n",
    "        people.sort(key=lambda x: [-x[0], x[1]])\n",
    "\n",
    "        queue = []\n",
    "\n",
    "        for peo in people:\n",
    "            if len(queue) > peo[1]:\n",
    "                queue.insert(peo[1], peo)\n",
    "            else:\n",
    "                queue.append(peo)\n",
    "\n",
    "        return queue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people = sorted(people, key = lambda x: (-x[0], x[1]))\n",
    "        i = 0\n",
    "        while i < len(people):\n",
    "            if i > people[i][1]:\n",
    "                people.insert(people[i][1], people[i])\n",
    "                people.pop(i+1)\n",
    "            i += 1\n",
    "        return people\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x:(x[0], -x[1]), reverse=True)\n",
    "        \n",
    "        res = []\n",
    "        for i in range(len(people)):\n",
    "            res.insert(people[i][1], people[i])\n",
    "\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# class Solution:\n",
    "#     def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "#         # 特殊情况处理\n",
    "        \n",
    "#         # init\n",
    "#         ans = []\n",
    "#         res = []\n",
    "#         # 把ki=0的和ki>=1的分开\n",
    "#         for p in people:\n",
    "#             h, k = p[0], p[1]\n",
    "#             if k == 0:\n",
    "#                 ans.append(p)\n",
    "#             else:\n",
    "#                 res.append(p)\n",
    "#         # ki=0的按hi升序排序\n",
    "#         ans.sort(key=lambda p:p[0])\n",
    "#         # # print('ans after sort:{}'.format(ans))\n",
    "#         # ki>=1的按照1.ki升序排序 2.hi降序排序\n",
    "#         res.sort(key=lambda p:(p[1], -p[0]))\n",
    "#         # # print('res after sort:{}'.format(res))\n",
    "\n",
    "#         def findIndex(ans, p):\n",
    "#             # 找到ans中第k个值>=h的元素下标\n",
    "#             h, k = p[0], p[1]\n",
    "#             # 遍历 (二分应该会)\n",
    "#             index = 0\n",
    "#             while k and index<len(ans):\n",
    "#                 if ans[index][0] >= h:\n",
    "#                     k -= 1\n",
    "#                 index += 1\n",
    "#             # print('the index of {}:{}'.format(p, index))\n",
    "#             return index\n",
    "\n",
    "#         for p in res:\n",
    "#             index = findIndex(ans, p)\n",
    "#             ans = ans[:index] + [p] + ans[index:]\n",
    "#             # print('after insert {}, ans:{}'.format(p, ans))\n",
    "#         return ans\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        n = len(people)\n",
    "        ans = list()\n",
    "        for person in people:\n",
    "            ans[person[1]:person[1]] = [person]\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort()\n",
    "        has=[0 for _ in range(len(people))]\n",
    "        res=[[] for _ in range(len(people))]\n",
    "        #对于身高最矮的,people[0][1]就是index位置，因为其他都比他高，他只能在其中一个位置\n",
    "        res[people[0][1]]=people[0]\n",
    "        has[people[0][1]]=1\n",
    "\n",
    "        #相等的情况会有点难\n",
    "        count=0\n",
    "        for i in range(1,len(people)):\n",
    "            count=0\n",
    "\n",
    "            for j in range(len(has)):\n",
    "                if has[j]==1 and res[j][0]==people[i][0]:\n",
    "                    count+=1\n",
    "                elif has[j]==0 and count==people[i][1]:\n",
    "                    res[j]=people[i]\n",
    "                    has[j]=1\n",
    "                    break\n",
    "                elif has[j]==0 and count<people[i][1]:\n",
    "                    count+=1\n",
    "        \n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 先按照h维度的身高顺序从高到低排序。确定第一个维度\n",
    "        # lambda返回的是一个元组：当-x[0](维度h）相同时，再根据x[1]（维度k）从小到大排序\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        que = []\n",
    "\t\n",
    "\t# 根据每个元素的第二个维度k，贪心算法，进行插入\n",
    "        # people已经排序过了：同一高度时k值小的排前面。\n",
    "        for p in people:\n",
    "            que.insert(p[1], p)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort()  # O(nlogn)\n",
    "        result = [[None, 0]] * len(people)\n",
    "\n",
    "        for h, k in people:  # O(n^2)\n",
    "            cnt = 0\n",
    "            for i, pair in enumerate(result):\n",
    "                if pair == [None, 0]:\n",
    "                    cnt += 1\n",
    "                else:\n",
    "                    if pair[0] >= h:\n",
    "                        cnt += 1\n",
    "                if cnt > k:\n",
    "                    result[i] = [h, k]\n",
    "                    break\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def __init__(self):\n",
    "        self.queue = []\n",
    "\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        for i in range(len(people)):\n",
    "            self.queue.insert(people[i][1], people[i])\n",
    "        return self.queue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "\n",
    "        # 08:45\n",
    "\n",
    "        n = len(people)\n",
    "\n",
    "        for i in range(n):\n",
    "            for j in range(1,n):\n",
    "                if people[j-1][0] < people[j][0] or (people[j-1][0] == people[j][0] and people[j-1][1] > people[j][1]):\n",
    "                    temp = people[j-1]\n",
    "                    people[j-1] = people[j]\n",
    "                    people[j] = temp\n",
    "        print(people)\n",
    "        result = []\n",
    "\n",
    "        for j in range(n):\n",
    "            if j == 0:\n",
    "                result.append(people[j])\n",
    "            else:\n",
    "\n",
    "# [7,0],[7,1],[6,1],[5,0],[5,2],[4,4]\n",
    "# [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]\n",
    "\n",
    "                target = people[j]\n",
    "\n",
    "                i = 0\n",
    "                while i < len(result):\n",
    "                    temp = result[i]\n",
    "                    if temp[1] == target[1]:\n",
    "                        if temp[0] > target[0]:\n",
    "                            result.insert(i,target)\n",
    "                        else:\n",
    "                            result.insert(i+1,target)\n",
    "                        break\n",
    "                    if i == target[1]-1:\n",
    "                        if temp[0] >= target[0]:\n",
    "                            result.insert(i+1,target)\n",
    "                        else:\n",
    "                            result.insert(i,target)\n",
    "                        break\n",
    "                    i = i + 1\n",
    "        \n",
    "        return result\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x:x[1])\n",
    "        result = []\n",
    "        for i in range(len(people)):\n",
    "            j, temp_ki = 0, 0\n",
    "            while j < len(result) and temp_ki < people[i][1]: # 找完所有的，或者找到了指定个数的\n",
    "                if result[j][0] >= people[i][0]:\n",
    "                    temp_ki += 1\n",
    "                j += 1\n",
    "            for _ in range(j,len(result)):\n",
    "                if result[j][0] < people[i][0]:\n",
    "                    j += 1\n",
    "                else:\n",
    "                    break\n",
    "            result.insert(j, people[i])\n",
    "        return result\n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people = sorted(people, key = lambda x : (-x[0], x[1]))\n",
    "        ret = []\n",
    "        for p in people:\n",
    "            ret.insert(p[1], p)\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        \n",
    "        result = []\n",
    "        # 按照排序後的順序，插入位置\n",
    "        for i in people:\n",
    "            result.insert(i[1], i)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "from functools import cmp_to_key\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=cmp_to_key(self.cmp))\n",
    "        ans = []\n",
    "        for p in people:\n",
    "            ans.insert(p[1], p)\n",
    "        return ans\n",
    "\n",
    "\n",
    "    def cmp(self, p1, p2):\n",
    "        return p2[0] - p1[0] if p1[0] != p2[0] else p1[1] - p2[1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key = lambda x:(x[0],-x[1]))\n",
    "        g=len(people)*[0]\n",
    "        left = 0\n",
    "        right = len(people)-1\n",
    "        l = left\n",
    "        r = right\n",
    "        def k(n):\n",
    "            if n >= len(people):\n",
    "                    return\n",
    "            for i in range(n):\n",
    "                if people[i][0]>=people[n][0]:\n",
    "                    g[n]+=1\n",
    "        res = [people.pop()]\n",
    "        for i in range(0, len(people)):\n",
    "            a = people.pop()\n",
    "            res.insert(a[1], a)\n",
    "\n",
    "                \n",
    "        return res\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people = sorted(people, key=lambda x:(-x[0], x[1])) # 需要是按身高降序，然后同身高按排位升序\n",
    "\n",
    "        i = 0\n",
    "        while i < len(people):\n",
    "            item = people.pop(i)\n",
    "            people.insert(item[1], item)\n",
    "            i+=1\n",
    "        \n",
    "        return people\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key  = lambda x :(x[0],-x[1]))\n",
    "        ret = [None] * len(people)\n",
    "        plen = len(people)\n",
    "\n",
    "        for i in range(plen):\n",
    "            h,k = people[i]\n",
    "            p  = 0\n",
    "            for j in range(plen):\n",
    "                if ret[j] == None:\n",
    "                    p +=1\n",
    "                    if p == k+1:\n",
    "                        break\n",
    "            ret[j] = people[i]\n",
    "        return ret\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 特殊情况处理\n",
    "        \n",
    "        # init\n",
    "        ans = []\n",
    "        res = []\n",
    "        # 把ki=0的和ki>=1的分开\n",
    "        for p in people:\n",
    "            h, k = p[0], p[1]\n",
    "            if k == 0:\n",
    "                ans.append(p)\n",
    "            else:\n",
    "                res.append(p)\n",
    "        # ki=0的按hi升序排序\n",
    "        ans.sort(key=lambda p:p[0])\n",
    "        # # print('ans after sort:{}'.format(ans))\n",
    "        # ki>=1的按照1.ki升序排序 2.hi降序排序\n",
    "        res.sort(key=lambda p:(p[1], -p[0]))\n",
    "        # # print('res after sort:{}'.format(res))\n",
    "\n",
    "        def findIndex(ans, p):\n",
    "            # 找到ans中第k个值>=h的元素下标\n",
    "            h, k = p[0], p[1]\n",
    "            # 遍历 （快速选择应该会更快）\n",
    "            index = 0\n",
    "            while k and index<len(ans):\n",
    "                if ans[index][0] >= h:\n",
    "                    k -= 1\n",
    "                index += 1\n",
    "            # print('the index of {}:{}'.format(p, index))\n",
    "            return index\n",
    "\n",
    "        for p in res:\n",
    "            index = findIndex(ans, p)\n",
    "            ans = ans[:index] + [p] + ans[index:]\n",
    "            # print('after insert {}, ans:{}'.format(p, ans))\n",
    "\n",
    " \n",
    "\n",
    "        return ans\n",
    "\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        #people=sorted(people,key=lambda x:x[0],reverse=True)\n",
    "        people.sort(key=lambda x:(-x[0],x[1]))\n",
    "        new_people=[]\n",
    "        for i in range(len(people)):\n",
    "            new_people.insert(people[i][1],people[i])\n",
    "        return new_people\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        que = []\n",
    "\n",
    "        for p in people:\n",
    "            que.insert(p[1], p)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        queue = []\n",
    "        for c in people:\n",
    "            queue.insert(c[1], c)\n",
    "        return queue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        result = []\n",
    "        for x in sorted(people, key=lambda x: (-x[0], x[1])):\n",
    "            result[x[1]:x[1]] = x,\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x:x[1])\n",
    "        result = []\n",
    "        for i in range(len(people)):\n",
    "            j, temp_ki = 0, 0\n",
    "            while j < len(result) and temp_ki < people[i][1]: # 找完所有的，或者找到了指定个数的\n",
    "                if result[j][0] >= people[i][0]:\n",
    "                    temp_ki += 1\n",
    "                j += 1\n",
    "            for _ in range(j,len(result)):\n",
    "                if result[j][0] < people[i][0]:\n",
    "                    j += 1\n",
    "                else:\n",
    "                    break\n",
    "            result.insert(j, people[i])\n",
    "        return result\n",
    "                \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        if len(people) == 1:\n",
    "            return people\n",
    "        # 从高个开始, 一个一个按自己前面有多少个身高>=自己的人插入\n",
    "        from functools import cmp_to_key\n",
    "        key = cmp_to_key(lambda x, y: y[0] - x[0] if x[0] != y[0] else x[1] -y[1])\n",
    "        people.sort(key=key)\n",
    "        res = []\n",
    "        for p in people:\n",
    "            res.insert(p[1], p)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        que = []\n",
    "        for p in people:\n",
    "            que.insert(p[1], p)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        res=[]\n",
    "        people = sorted(people, key = lambda x: (-x[0], x[1]))\n",
    "        for p in people:\n",
    "            if len(res)<=p[1]:\n",
    "                res.append(p)\n",
    "            elif len(res)>p[1]:\n",
    "                res.insert(p[1],p)\n",
    "        return res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort()\n",
    "        print(people)\n",
    "        for i in range(len(people)-1,-1,-1):\n",
    "            if people[i][1]>0:\n",
    "                num=people[i][1]\n",
    "                j=i-1\n",
    "                while j>=0 and people[i][0]==people[j][0]:\n",
    "                    num-=1\n",
    "                    j-=1\n",
    "                if num<=0:\n",
    "                    continue\n",
    "                \n",
    "                people.insert(i+num,people.pop(i))\n",
    "        return people\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# 本题有两个维度，h和k，看到这种题目一定要想如何确定一个维度，然后再按照另一个维度重新排列。\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "    \t# 先按照h维度的身高顺序从高到低排序。确定第一个维度\n",
    "        # lambda返回的是一个元组：当-x[0](维度h）相同时，再根据x[1]（维度k）从小到大排序\n",
    "        # 那么只需要按照k为下标重新插入队列就可以了，为什么呢？\n",
    "        people.sort(key = lambda x : (-x[0], x[1]) )\n",
    "        que = []\n",
    "\n",
    "        for i in range(len(people)):\n",
    "            que.insert(people[i][1], people[i])\n",
    "        \n",
    "        return que\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people = sorted(people, key = lambda x:(-x[0],x[1]))\n",
    "        n = len(people)\n",
    "        ans = list()\n",
    "        for p in people:\n",
    "            ans[p[1]:p[1]] = [p]\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort()\n",
    "        #print(people)\n",
    "        for i in range(len(people)-1,-1,-1):\n",
    "            if people[i][1]>0:\n",
    "                num=people[i][1]\n",
    "                j=i-1\n",
    "                while j>=0 and people[i][0]==people[j][0]:\n",
    "                    num-=1\n",
    "                    j-=1\n",
    "                if num<=0:\n",
    "                    continue\n",
    "                \n",
    "                people.insert(i+num,people.pop(i))\n",
    "        return people\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        ans = []\n",
    "        for p in people:\n",
    "            ans.insert(p[1], p)\n",
    "        return ans\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def custom_sort(self,a, b):\n",
    "        if a[0] > b[0]:\n",
    "            return -1\n",
    "        elif a[0] < b[0]:\n",
    "            return 1\n",
    "        else:\n",
    "            if a[1] < b[1]:\n",
    "                return -1\n",
    "            elif a[1] > b[1]:\n",
    "                return 1\n",
    "            else:\n",
    "                return 0\n",
    "\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        #先排序，h从大到小，k从小到大\n",
    "        #再逐个插入queue\n",
    "        #这样就能满足同样的k，h从小到大；同样的h，k从小到大\n",
    "        #写代码，这里主要是抄的，因为主要是python中复杂排序的数据结构\n",
    "\n",
    "        #用gpt写的更普适的cmp函数\n",
    "        people = sorted(people, key=cmp_to_key(self.custom_sort))\n",
    "\n",
    "        #people.sort(key = lambda x: (-x[0],x[1]))\n",
    "        q = []\n",
    "        for i in range(len(people)):\n",
    "            q.insert(people[i][1],people[i])\n",
    "        return q\n",
    "\n",
    "    \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key = lambda x:(-x[0],x[1]))\n",
    "        que = []\n",
    "        for p in people:\n",
    "            que.insert(p[1],p)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 贪心\n",
    "        # people.sort(key=lambda x :(-x[0], x[1]))\n",
    "        # que = []\n",
    "        # for q in people:\n",
    "        #     que.insert(q[1], q)\n",
    "        # return que\n",
    "        # 详细注释\n",
    "        # 先按照h维度的身高顺序从高到低排序。确定第一个维度\n",
    "        # lambda返回的是一个元组：当-x[0](维度h）相同时，再根据x[1]（维度k）从小到大排序\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        que = []\n",
    "\t\n",
    "\t    # 根据每个元素的第二个维度k，贪心算法，进行插入\n",
    "        # people已经排序过了：同一高度时k值小的排前面。\n",
    "        for p in people:\n",
    "            que.insert(p[1], p)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x:x[0]*10000000-x[1],reverse=True)\n",
    "        result=[]\n",
    "        for i in range(len(people)):\n",
    "            result.insert(people[i][1],people[i])\n",
    "        return result\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        result = []\n",
    "        people = sorted(people,key=lambda x:(-x[0],x[1]))\n",
    "        for i in people:\n",
    "            if len(result)<=i[1]:\n",
    "                result.append(i)\n",
    "            else:\n",
    "                result.insert(i[1],i)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key = lambda x:(-x[0],x[1]))\n",
    "        que = []\n",
    "        for d in people:\n",
    "            que.insert(d[1],d)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "# ***\n",
    "class Solution:\n",
    "    # 局部最优：优先按身高高的people的k来插入。插入操作过后的people满足队列属性\n",
    "    # 全局最优：最后都做完插入操作，整个队列满足题目队列属性\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 先按照h维度的身高顺序从高到低排序。确定第一个维度\n",
    "        # lambda返回的是一个元组：当-x[0](维度h）相同时，再根据x[1]（维度k）从小到大排序\n",
    "        people.sort(key = lambda x:(-x[0],x[1]))\n",
    "        \n",
    "        result = []\n",
    "        # 根据每个元素的第二个维度k，贪心算法，进行插入\n",
    "        # people已经排序过了：同一高度时k值小的排前面。\n",
    "        for i in people:\n",
    "            result.insert(i[1],i)\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        if len(people) <= 1:\n",
    "            return people\n",
    "        people = sorted(people, key = lambda x: (x[0], -x[1]))\n",
    "\n",
    "        n = len(people)\n",
    "        new_people = [-1] * n               # 初始化新队列\n",
    "        index = list(range(n))              # 建立一个列表来维护新队列\"空位\"集合\n",
    "        for i in people:\n",
    "            new_index = index[i[1]]         # \"空位\"集合中的第k个元素就是学生在新队列中的位置\n",
    "            new_people[new_index] = i       # 根据新位置将学生放入新队列\n",
    "            index.pop(i[1])                 # 该位置已站人，更新\"空位\"集合\n",
    "        return new_people"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key = lambda x:[-x[0],x[1]])\n",
    "        que = []\n",
    "\n",
    "        for p in people:\n",
    "            que.insert(p[1],p)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        result = []\n",
    "        for p in people:\n",
    "            result.insert(p[1], p)\n",
    "        return result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        n  = len(people)\n",
    "        b = [[-1,-1] for i in range(n)]\n",
    "        people.sort()\n",
    "        for i in range(n):\n",
    "            k = people[i][1]\n",
    "            for j in range(n):\n",
    "                if k == 0 and b[j][0] == -1:\n",
    "                    b[j] = people[i]\n",
    "                    break \n",
    "                elif b[j][0] == -1 or b[j][0] >= people[i][0]:\n",
    "                    k -= 1\n",
    "        return b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 贪心，涉及到两个维度，分开贪心，一次只解决一个维度\n",
    "        # 1. 先按照身高降序排列，同身高时按照第二个维度升序排列\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        que = []\n",
    "\n",
    "        for p in people:\n",
    "            # 2. 依次对应位置即可，由于身高已经将序，那么前面有多少个人身高大于或等于当前值，就插入到什么位置\n",
    "            que.insert(p[1], p)\n",
    "        return que\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        sorted_people = sorted(people,key = lambda x : (-x[0],x[1]))\n",
    "        for i in range(0,len(sorted_people)):\n",
    "            if sorted_people[i][1] != i:\n",
    "                p = sorted_people.pop(i)\n",
    "                sorted_people.insert(p[1],p)\n",
    "        return sorted_people"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: list[list[int]]) -> list[list[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        index = 0\n",
    "        while index < len(people):\n",
    "            if people[index][1] < index:\n",
    "                tmp = people[index]\n",
    "                people.pop(index)\n",
    "                people.insert(tmp[1], tmp)\n",
    "            index += 1\n",
    "        return people"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        ans = []\n",
    "        for i in range(len(people)):\n",
    "            ans.insert(people[i][1], people[i])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people = sorted(people, key = lambda x : (-x[0], x[1]))\n",
    "        ret = []\n",
    "        for p in people:\n",
    "            ret.insert(p[1], p)\n",
    "        return ret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        nul = []\n",
    "        people.sort(key = lambda x:(-x[0],x[1]))\n",
    "        for val in people:\n",
    "            nul.insert(val[1],val)\n",
    "        return nul"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        res=[]\n",
    "        people=sorted(people,key=lambda x:(-x[0],x[1]))\n",
    "        for p in people:\n",
    "            if len(res)<=p[1]:\n",
    "                res.append(p)\n",
    "            else:\n",
    "                res.insert(p[1],p)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people = sorted(people, key= lambda x: (x[0], x[1]))\n",
    "        n = len(people)\n",
    "        ans = [None] * n\n",
    "        for i in range(n):\n",
    "            if i == 0:\n",
    "                ans[people[i][1]] = people[i]\n",
    "            else:\n",
    "                if people[i][0] > people[i-1][0]:\n",
    "                    k = people[i][1]\n",
    "                    index = -1\n",
    "                    while k >=0 and index+1 <= n-1:\n",
    "                        if ans[index+1] is None:\n",
    "                            index +=1\n",
    "                            k -= 1\n",
    "                        else:\n",
    "                            index +=1\n",
    "                    ans[index] = people[i]\n",
    "                if people[i][0] == people[i-1][0]:\n",
    "                    k = people[i][1]\n",
    "                    index = -1\n",
    "                    while k>=0 and index +1 <= n-1:\n",
    "                        if ans[index+1] is None or ans[index+1][0] == people[i][0]:\n",
    "                            index +=1\n",
    "                            k -=1\n",
    "                        else:\n",
    "                            index +=1\n",
    "                    ans[index] = people[i]\n",
    "        return ans\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key = lambda x:(-x[0],x[1]))\n",
    "        que = []\n",
    "        for p in people:\n",
    "            que.insert(p[1],p)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        result = []\n",
    "        for h, k in people:\n",
    "            result.insert(k, [h, k])\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # 套路 先倒序排列，再用插入法，插入到p[1]的位置，就会插队相同数量的前面\n",
    "        people = sorted(people, key=lambda x: (-x[0], x[1]))\n",
    "        res = []\n",
    "        for p in people:\n",
    "            if len(res) <= p[1]:\n",
    "                res.append(p)\n",
    "            elif len(res) > p[1]:\n",
    "                res.insert(p[1], p)\n",
    "        return res\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        res=[]\n",
    "        people=sorted(people,key=lambda x:(-x[0],x[1]))\n",
    "        for p in people:\n",
    "            if len(res)<=p[1]:\n",
    "                res.append(p)\n",
    "            elif len(res)>p[1]:\n",
    "                res.insert(p[1],p)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    from functools import cmp_to_key\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=cmp_to_key(self.compare),reverse=True)\n",
    "        queue=[]\n",
    "        for item in people:\n",
    "            queue.insert(item[1],item)\n",
    "        return queue\n",
    "    def compare(self,item1,item2):\n",
    "        if item1[0]>item2[0]:\n",
    "            return 1\n",
    "        elif item1[0]==item2[0] and item1[1]<item2[1]:\n",
    "            return 1\n",
    "            # if item1[1]<item2[1]:\n",
    "            #     return 1\n",
    "            # elif item1[1]==item2[1]:\n",
    "            #     return 0\n",
    "            # else:\n",
    "            #     return -1\n",
    "        else:\n",
    "            return -1\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        #根据身高排序\n",
    "        #对每个人的ki保留更高的人的位置，即位置为第ki+1个空位置\n",
    "\n",
    "        #1.(5,2)要在(5,0)前面先留空位\n",
    "\n",
    "        for j in range(len(people)):                      # people.sort(key=lambda x: (x[0], -x[1]))\n",
    "            for i in range(len(people)-1):\n",
    "                if people[i][0]>people[i+1][0]:\n",
    "                    index = people[i]\n",
    "                    people[i] = people[i+1]\n",
    "                    people[i+1] = index\n",
    "                if people[i][0] == people[i+1][0]:\n",
    "                    if people[i][1]<people[i+1][1]:\n",
    "                        index = people[i]\n",
    "                        people[i] = people[i+1]\n",
    "                        people[i+1] = index\n",
    "        result = [None] * len(people)\n",
    "        print(people)\n",
    "        for k in people:\n",
    "            k_num = 0\n",
    "            idx = 0\n",
    "            while idx < len(people):\n",
    "                if result[idx] == None:\n",
    "                    if k[1] == k_num:\n",
    "                        result[idx] = k\n",
    "                        break\n",
    "                    else:\n",
    "                        k_num += 1\n",
    "                idx += 1\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        #根据身高排序\n",
    "        #对每个人的ki保留更高的人的位置，即位置为第ki+1个空位置\n",
    "\n",
    "        for j in range(len(people)):\n",
    "            for i in range(len(people)-1):\n",
    "                if people[i][0]>people[i+1][0]:\n",
    "                    index = people[i]\n",
    "                    people[i] = people[i+1]\n",
    "                    people[i+1] = index\n",
    "                if people[i][0] == people[i+1][0]:\n",
    "                    if people[i][1]<people[i+1][1]:\n",
    "                        index = people[i]\n",
    "                        people[i] = people[i+1]\n",
    "                        people[i+1] = index\n",
    "        result = [None] * len(people)\n",
    "        print(people)\n",
    "        for k in people:\n",
    "            k_num = 0\n",
    "            idx = 0\n",
    "            while idx < len(people):\n",
    "                if result[idx] == None:\n",
    "                    if k[1] == k_num:\n",
    "                        result[idx] = k\n",
    "                        break\n",
    "                    else:\n",
    "                        k_num += 1\n",
    "                idx += 1\n",
    "        return result\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        que = []\n",
    "\t\n",
    "        for p in people:\n",
    "            que.insert(p[1], p)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x:(-x[0],x[1]))\n",
    "        res=[]\n",
    "        for item in people:\n",
    "            res.insert(item[1],item)\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "\n",
    "        people = sorted(people, key = lambda x: (-x[0],x[1]))\n",
    "\n",
    "        res = []\n",
    "        for person in people:\n",
    "\n",
    "            res.insert(person[1],person)\n",
    "        return res "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        n = len(people)\n",
    "        res = []\n",
    "\n",
    "        if not people:\n",
    "            return [[]]\n",
    "            \n",
    "        people = sorted(people, key = lambda x: (-x[0], x[1]))\n",
    "                        \n",
    "        for person in people:\n",
    "            if person[1] >= len(res):\n",
    "                res.append(person)\n",
    "            else:\n",
    "                res.insert(person[1], person)\n",
    "                        \n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "\n",
    "        people.sort(key= lambda x : (-x[0],x[1]))\n",
    "        res = []\n",
    "        for h,num in people:\n",
    "            if num >= len(res):\n",
    "                res.append([h,num])\n",
    "            else:\n",
    "                res.insert(num,[h,num])\n",
    "        return res"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people = sorted(people, key = lambda x: (-x[0],x[1]))\n",
    "        que = []\n",
    "        for i in people:\n",
    "            que.insert(i[1],i)\n",
    "        return que"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "# 两维度的贪心，固定一个维度 sort函数  insert\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key=lambda x: (-x[0], x[1]))\n",
    "        ans = []\n",
    "        for value in people:\n",
    "            ans.insert(value[1], value[:])\n",
    "        return ans"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    from functools import cmp_to_key\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        # people.sort(key=cmp_to_key(self.compare),reverse=True)\n",
    "        people.sort(key=lambda x:(x[0],-x[1]),reverse=True)\n",
    "        queue=[]\n",
    "        for item in people:\n",
    "            queue.insert(item[1],item)\n",
    "        return queue\n",
    "    def compare(self,item1,item2):\n",
    "        if item1[0]>item2[0]:\n",
    "            return 1\n",
    "        elif item1[0]==item2[0] and item1[1]<item2[1]:\n",
    "            return 1\n",
    "            # if item1[1]<item2[1]:\n",
    "            #     return 1\n",
    "            # elif item1[1]==item2[1]:\n",
    "            #     return 0\n",
    "            # else:\n",
    "            #     return -1\n",
    "        else:\n",
    "            return -1\n",
    "            "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import List\n",
    "import collections\n",
    "\n",
    "class Solution:\n",
    "    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:\n",
    "        people.sort(key = lambda x: (-x[0], x[1]))\n",
    "        queue = []\n",
    "        for item in people:\n",
    "            if len(queue) <= item[1]:\n",
    "                queue.append(item)\n",
    "            else:\n",
    "                queue.insert(item[1], item)\n",
    "        return queue"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 2
}
